package dwz.cms.article.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import dwz.cms.article.common.ArticleStatus;
import dwz.cms.article.common.Constants;
import dwz.cms.article.common.HtmlUtil;
import dwz.cms.article.util.ftp.FTPUtils;
import dwz.cms.article.util.ftp.FtpError;
import dwz.cms.article.util.ftp.MyFTPFile;
import dwz.persistence.beans.Article;
import dwz.persistence.beans.CmsArtChannel;
import dwz.persistence.beans.CmsArticleDraft;
import dwz.persistence.mapper.ArticleMapper;
import dwz.persistence.mapper.CmsArtChannelMapper;
import dwz.persistence.mapper.CmsArticleDraftMapper;

/**
 * Created by Eclipse
 * 
 * @author : Yating
 * @version:2017年4月24日 上午10:03:08 ArticleDraft 操作服务
 */
@Service("articleDraftOpeService")
public class ArticleDraftOpeService implements IArticleOpe {

	/**
	 * 数据库操作DAO
	 */
	@Resource
	CmsArticleDraftMapper cmsArticleDraftMapper;

	@Resource
	CmsArtChannelMapper cmsArtChannelMapper;

	@Resource
	ArticleMapper articleMapper;

	@Resource
	private SysStaticconnectionService sysStaticconnectionService;
	@Resource
	private ArticleDispService articleDispService;

	/**
	 * 修改用户初次上传的文章内容，添加ID，时间，超时时间等必要信息。
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public void saveArticle(Article article, Object parameters) {
		// TODO Auto-generated method stub
		// CmsArticleDraft draftArticle = (CmsArticleDraft) article;

		Date date = new Date();

		if ("".equals(article.getCode()) || article.getCode() == null) {
			String tempString = HtmlUtil.generateCode(date);
			article.setCode(tempString);
			article.setWebpath(tempString);
		} else {
			article.setWebpath(article.getCode());
		}

		article.setCreatetime(date);
		article.setExpiretime(HtmlUtil.generateExpiryDate(date, Calendar.YEAR, Constants.EXPIRE_DURATION));
		article.setState(ArticleStatus.草稿.getStatus());

		articleMapper.insertDraft(article);

		// Map m = (Map) parameters;
		// String ids = (String) m.get("channelids");
		String currentCode = (String) article.getCode();

		Short channeltop = 0;
		synchronizeChannel(currentCode, article.getChannelids(), channeltop);
	}

	/**
	 * 修改文章
	 */
	@Override
	public int updateArticle(Article article, Object parameters) {
		// TODO Auto-generated method stub

		article.setState(ArticleStatus.草稿.getStatus());
		articleMapper.updateByCode(article);

		String currentCode = (String) article.getCode();

		Short channeltop = 0;
		synchronizeChannel(currentCode, article.getChannelids(), channeltop);

		return 0;
	}

	/**
	 * 删除 或 撤销 文章
	 */
	@Override
	public void delArticle(Article article,String channelList) {
		Short sState = article.getState();

		if (sState == 3 || sState == 4) {// 状态是 已发布 或 待发布 的稿件,不可直接删除,需将状态转为 已撤销 并从cms_article_publish表 中移动到 cms_article_draft表中
			article.setState((short) 5);
			articleMapper.insertDraft(article);
			articleMapper.delPublishByPrimaryKey(article.getCode());

			// TODO 对应静态化页面的删除

		}else if (sState==0||sState==5){
			articleMapper.delDraftByPrimaryKey(article.getCode());
			
			// TODO 此处应该还有问题 channelids 的获取 及channeltop的处理
			Short channeltop = 0;
			synchronizeChannel(article.getCode(), channelList, channeltop);
			

			// TODO 对应静态化页面的删除
		}
	}

	/**
	 * 发布文章
	 */
	@Override
	public String pubArticle(String codeList, String channelid) {
		String resultStr = "";

		try {
			resultStr = doUpload(codeList, channelid).toString();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// synchronizeChannel(currentCode, ids, channeltop);

		return resultStr;

	}

	/**
	 * 文章置顶(非首页)
	 * 
	 * @param code
	 *            文章code
	 * @param channelid
	 *            待置顶的频道
	 * @throws Exception
	 *             异常错误处理
	 */
	@Override
	public String saveTopisNotFirst(String code, String channelid) {
		if (!code.isEmpty() && !channelid.isEmpty()) {
			try {
				CmsArtChannel artChannel = cmsArtChannelMapper.selectCmsArtChannelByCodeChannelid(code, channelid);
				// 判断记录是否已经存在
				if (artChannel != null) {
					// 记录存在,获取该channelid下最大的seq
					int maxseq = cmsArtChannelMapper.getMaxSeqByChannelid(channelid) + 1;
					artChannel.setSeq(maxseq);
					artChannel.setChanneltop(Short.parseShort("1"));
					cmsArtChannelMapper.update(artChannel);

					return "稿件置顶成功";

				} else {
					return "您选择的稿件不存在，无法置顶！";
				}
			} catch (Exception e) {
				// TODO: handle exception
				return "稿件置顶失败！";
			}
		} else {
			return "您选择的稿件不存在，无法置顶！";
		}
	}

	/**
	 * 
	 * 文章置顶(首页)
	 */
	public void saveTopisFirst(String code, Integer channelid) throws Exception {

		if (!code.isEmpty() && channelid != -1) {
			try {
				List<CmsArtChannel> artChannelList = cmsArtChannelMapper.selectCmsArtChannelByCode(code);

				if (artChannelList != null && artChannelList.size() != 0) {
					// 判断记录是否已经存在
				}
			} catch (Exception e) {
				// TODO: handle exception
			}

		}
	}

	/**
	 * 取消稿件置顶(非首页)
	 * 
	 * @param code
	 * @param channelid
	 * @return
	 */
	@Override
	public String unsaveTopisNotFirst(String code, String channelid) {
		if (!code.isEmpty() && !channelid.isEmpty()) {
			try {
				CmsArtChannel artChannel = cmsArtChannelMapper.selectCmsArtChannelByCodeChannelid(code, channelid);
				// 判断记录是否已经存在
				if (artChannel != null) {
					// 记录存在,将channeltop和seq置为0
					// int
					// maxseq=cmsArtChannelMapper.getMaxSeqByChannelid(channelid)+1;
					artChannel.setSeq(0);
					artChannel.setChanneltop(Short.parseShort("0"));
					cmsArtChannelMapper.update(artChannel);

					return "取消稿件置顶成功";

				} else {
					return "您选择的稿件不存在，无法取消置顶！";
				}
			} catch (Exception e) {
				// TODO: handle exception
				return "取消稿件置顶失败！";
			}
		} else {
			return "您选择的稿件不存在，无法取消置顶！";
		}
	}

	/**
	 * 同步Cms_art_channel 表
	 * 
	 * @param code
	 * @param ids
	 * @param channeltop
	 */
	public void synchronizeChannel(String code, String ids, Short channeltop) {
		if (code.isEmpty() || ids.isEmpty())
			return;

		boolean isExist = false;

		List<String> cList = Arrays.asList(ids.split(","));
		ArrayList<String> idList = new ArrayList<String>();
		idList.addAll(cList);

		// 根据code查找cms_art_channel表
		List<CmsArtChannel> acList = cmsArtChannelMapper.selectCmsArtChannelByCode(code);

		// 遍历该文章在cms_art_channel中的记录
		for (CmsArtChannel acMap : acList) {
			isExist = false;
			// 查看这条记录中的channelid在channelids(idList)中是否存在,如果存在isExist设为true,并在idList中移除这个id记录
			for (String id : idList) {
				if ((Integer) acMap.getChannelid() == Integer.parseInt(id)) {
					isExist = true;
					idList.remove(id);
					break;
				}
			}
			
			if (!isExist) {// 如果isExist为false,则该条记录中的channelid在idList中不存在,即修改文章后,在所属频道中取消了这个频道,所以再要将cms_art_channel表中将这条记录删除
				CmsArtChannel cac = new CmsArtChannel();
				cac.setId((Integer) acMap.getId());
				cac.setChannelid((Integer) acMap.getChannelid());
				cmsArtChannelMapper.delete(cac);
			} 
		}
		for (String id : idList) {
			CmsArtChannel cac = new CmsArtChannel();
			cac.setChannelid(Integer.parseInt(id));
			cac.setCode(code);
			cac.setIsfirst(Short.parseShort("0"));
			cac.setChanneltop(Short.parseShort("0"));
			cac.setFirsttop(Short.parseShort("0"));
			cac.setSeq(0);

			cmsArtChannelMapper.insert(cac);
		}
	}

	/**
	 * 生成静态并上传
	 * 
	 * @param dataSetMap
	 * @param parameters
	 * @return
	 * @throws DoradoException
	 */
	public Object doUpload(String codeListstr, String channelid) throws IOException {
		// 根据code 获取文章列表

		List<String> codeList = Arrays.asList(codeListstr.split(","));

		List<Article> cmsArticlePublishs = null;

		try {
			// 需要发布的文章列表
			// cmsArticlePublishs
			// =articleDispService.getArticleByCodeList(codeList);
			cmsArticlePublishs = articleMapper.selectArticleListByCodeList(codeList);

			sysStaticconnectionService.setFileRoot(Constants.CMS_STATIC_ROOT + "Static/");
			sysStaticconnectionService.setFiles(new Vector<MyFTPFile>());
			sysStaticconnectionService.setOperation(FTPUtils.UPLOAD);
			FtpError ftpResult = HtmlUtil.upLoadFiles(// sysStaticconnectionService.buildWholeSite());
					sysStaticconnectionService.buildStaticPages(cmsArticlePublishs));

			Map outParameters = new HashMap();
			for (Iterator iterator = ftpResult.getHashtable().keySet().iterator(); iterator.hasNext();) {
				Object hostName = (Object) iterator.next();
				String op = ftpResult.getMethodName().toUpperCase();
				String msg = (String) ftpResult.getHashtable().get(hostName);
				if (msg == null || msg.isEmpty()) {
					throw new IOException("FTP服务器异常: " + hostName);
				} else if (msg.contains("fail")) {
					throw new IOException("文章发送FTP服务器失败: " + hostName);
				} else {
					outParameters.put("$message", cmsArticlePublishs.size() + "篇文章已成功发布到远程服务器");
				}
			}
			return outParameters;

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}
}
